/* eslint-disable jsx-a11y/anchor-is-valid */
/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-10-26 17:05:31
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-04-29 10:29:11
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useEffect, useRef, useState } from 'react'
import { Button, Popconfirm, Space, Switch } from 'antd';
import PageDiv from '@/components/PageDiv';
import { DictDataDomain, CorpDomain } from '@/type.d/system';
import { ActionType, ProColumns, ProFormDateRangePicker, ProFormInstance, ProFormSelect, ProFormText, QueryFilter } from '@ant-design/pro-components';
import ResizeTable from '@/components/ResizeTable';
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { useStore } from '@/store';
import {
    changeStatus,
    getCorpList,
    removeCorp,
} from '@/api/system/corp';
import './index.less';
import CorpCard from './corpCard';


const Corp: React.FC = () => {
    const { layoutStore, userStore } = useStore();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<CorpDomain>>();
    const [queryValue, setQueryValue] = useState<CorpDomain>({});
    const [statusOptions, setStatusOptions] = useState<any[]>([]);
    const [tableListDataSource, setTableListDataSource] = useState<CorpDomain[]>([]);
    const [cardData, setCardData] = useState<CorpDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);

    const newdata = {
        taxpayerid: '',
        pkFathercorp: '',
        enablestate: '0',
        remark: '',
    }

    const columns: ProColumns<CorpDomain>[] = [
        {
            title: '主键',
            dataIndex: 'pkCorp',
            fixed: 'left',
            hideInTable: true
        },
        {
            title: '公司编码',
            dataIndex: 'corpCode',
            fixed: 'left'
        },
        {
            title: '公司名称',
            dataIndex: 'corpName',
            fixed: 'left'
        },
        {
            title: '企业信用代码',
            dataIndex: 'taxpayerid',
            fixed: 'left'
        },
        {
            title: '启用状态',
            dataIndex: 'enablestate',
            fixed: 'left',
            valueType: 'switch',
            // fieldProps: {
            //     options: statusOptions
            // },
            render: (_dom, record) => {
                return userStore.hasPerms('system:corp:add') ? <Popconfirm
                    title={record.enablestate === '0' ? '是否停用该公司？' : '是否启用该公司？'}
                    onConfirm={() => {
                        layoutStore.OpenSpanning()
                        changeStatus({ ...record, enablestate: record.enablestate === '0' ? '1' : '0' }).then((res) => {
                            setTableListDataSource(tableListDataSource.map((item) => {
                                if (item.pkCorp === res.data.pkCorp) {
                                    return res.data
                                } else {
                                    return item
                                }
                            }))
                        }).finally(() => {
                            layoutStore.CloseSpanning()
                        });
                    }}
                    okText="是"
                    cancelText="否"
                >
                    <Switch size='small' checked={record.enablestate === '0'} />
                </Popconfirm> : <Switch size='small' checked={record.enablestate === '0'} />
            },
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            fixed: 'left'
        },
        {
            title: '地址',
            dataIndex: 'address',
            fixed: 'left',
            valueType: 'text',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'date',
            fixed: 'left'
        },
        {
            title: '操作',
            width: 180,
            dataIndex: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: CorpDomain) => [
                <a key="add" hidden={!userStore.hasPerms('system:corp:add')} onClick={() => {
                    toCard({ pkFathercorp: entity.pkCorp }, true)
                }}>新增</a>,
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" hidden={!userStore.hasPerms('system:corp:edit')} onClick={() => {
                    toCard(entity, true)
                }}>修改</a>,
                <a key="delete" hidden={!userStore.hasPerms('system:corp:delete')}>
                    <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                        onDelete(entity)
                    }}>
                        删除
                    </Popconfirm>
                </a>


            ],
        },
    ];

    const headButton = () => {
        return <Space>
            <Button
                hidden={!userStore.hasPerms('system:corp:add')}
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard(newdata, true)}
            >
                新增
            </Button>
        </Space>
    }

    const toCard = (data: CorpDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }


    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])


    const onView = (data: CorpDomain) => {
        toCard(data)
    }

    const onDelete = (dedata: CorpDomain) => {
        if (dedata.pkCorp) {
            layoutStore.OpenSpanning()
            removeCorp(dedata.pkCorp).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.pkCorp !== dedata.pkCorp
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }
    }

    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }
        layoutStore.OpenSpanning();
        getCorpList({ ..._data }).then((res) => {
            setTableListDataSource(res.data)

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }


    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_normal_disable').then((res) => {
            const data = res.data;
            if (data['sysNormalDisable']) {
                const d: [] = data['sysNormalDisable'];
                setStatusOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))

            }
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])


    return (<PageDiv>{

        pageStatus === 'List' ? <PageDiv>
            <QueryFilter<CorpDomain>
                defaultCollapsed
                split
                span={4}
                onFinish={onQuery}
                formRef={queryformRef}>
                <ProFormText key='corpName' name="corpName" label="公司名称" />
                <ProFormText key='corpCode' name="corpCode" label="公司编码" />
                <ProFormSelect key='enablestate' name="enablestate" label="启用状态" options={statusOptions} />
                <ProFormDateRangePicker key='createTime' name="createTime" label="创建时间" />
            </QueryFilter>
            <ResizeTable<CorpDomain>
                onRow={record => {
                    return {
                        onDoubleClick: event => { onView(record) },
                    };
                }}
                dataSource={tableListDataSource}
                actionRef={actionRef}
                columns={columns}
                cardBordered
                revalidateOnFocus={false}
                headerTitle={headButton()}
                pagination={false}
                rowKey={"pkCorp"}
            >
            </ResizeTable>
        </PageDiv >
            :
            <CorpCard
                onBack={() => setPageStatus('List')}
                isedit={isedit}
                setIsedit={setIsedit}
                statusOptions={statusOptions}
                cardData={cardData}
                newdata={newdata}
                tableListDataSource={tableListDataSource}
                setTableListDataSource={setTableListDataSource} />}
    </PageDiv>
    )
}
export default Corp;